<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Chat Application</title>
    <script th:src="@{/webjars/sockjs-client/1.0.2/sockjs.min.js}"></script>
    <script th:src="@{/webjars/stomp.js/2.3.3/stomp.min.js}"></script>
    <script>
        var stompClient = null;

        function connect() {
            var socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/messages', function (message) {
                    showMessage(JSON.parse(message.body));
                });
            });
        }

        function sendMessage() {
            var text = document.getElementById('message').value;
            stompClient.send("/app/chat", {}, JSON.stringify({'message': text}));
        }

        function showMessage(message) {
            var messages = document.getElementById('messages');
            var newMessage = document.createElement('li');
            newMessage.innerHTML = message.message;
            messages.appendChild(newMessage);
        }

        window.onload = function () {
            connect();
        };
    </script>
</head>
<body>
<ul id="messages"></ul>
<input type="text" id="message" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
</body>
</html>
